/**
    Copyright (C) 2013  Rodrigo Garcia

 This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include <avr/io.h>
#include "usart.h"
// ----

void usart_init(void){
	/* Set Port Inputs*/
	DDRD &= ~((1<<PD0)|(1<<PD1));
	//	#include <util/setbaud.h>
	usart_baud_38400();
	/* UBRRH = UBRRH_VALUE; */
	/* UBRRL = UBRRL_VALUE; */

	/* #if USE_2X */
	/* 	UCSRA |= (1 << U2X); */
	/* #else */
	/* 	UCSRA &= ~(1 << U2X); */
	/* #endif */

	/* Enable receiver and transmitter */
	UCSRB = (1<<RXEN)|(1<<TXEN);

	/* Set frame format: 8data, 1stop bit */
	UCSRC = (1<<URSEL)|(3<<UCSZ0);
}

// Note.- Baud Rates calculated only to a 8Mhz Clk
// * See datasheet page 169
void usart_baud_38400(void)
{
    UBRRH = 0x00;
    UBRRL = 0x0C;      //datasheet pag 169
}

void usart_baud_9600(void)
{
    UBRRH = 0x00;
    UBRRL = 0x33;      //datasheet pag 169
}

#define tx_ready() ( UCSRA & (1<<UDRE))


void usart_tx(char data){
	/* Wait for empty transmit buffer */
	while ( !tx_ready())
		;
	/* Put data into buffer, sends the data */
	UDR = data;
}

#define rx_ready() (UCSRA & (1<<RXC))

char usart_rx(void){
	/* Wait for data to be received */
	while ( !rx_ready() )
		;
	/* Get and return received data from buffer */
	return UDR;
}

char usart_rx_1s(void)
{
    /*Solo para probar espera hasta arpox 1600000 ciclos la respuesta si no sale*/
    uint32_t c=1600000;
    while( !rx_ready() )
    {
        if(!c--)
            return 0;
    }
    return UDR;

}

/* /\* ------ stdio management ------- *\/ */

/* void usart_putchar(char c, FILE* stream) */
/* { */
/*   usart_tx(c); */
/* } */

/* FILE usart=FDEV_SETUP_STREAM(usart_putchar,usart_getchar,_FDEV_SETUP_RW); */

/* void usart_printf_init(void) */
/* { */
/*   usart_init(); */
/*   stdout = &usart; */
/*   stdin=&usart; */
/* } */

/* /\* ---------------------------- *\/ */
